package com.springcloud.microservice.controller;

import com.google.common.collect.Maps;
import com.springcloud.microservice.ZuulAggregationApplication;
import com.springcloud.microservice.entities.User;
import com.springcloud.microservice.service.AggregationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import rx.Observable;
import rx.Observer;

import java.util.HashMap;

/**
 * Author : 周世雄 <br>
 * Date : 2018/11/26 14:38 <br>
 * E-mail : zhoushixiong@chinasoftinc.com
 * Description :
 */
@RestController
public class AggregationController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZuulAggregationApplication.class);

    @Autowired
    private AggregationService aggregationService;

    @GetMapping("/aggregate/{id}")
    public DeferredResult<HashMap<String, User>> aggregate(@PathVariable Long id) {
        Observable<HashMap<String, User>> result = this.aggregationObservable(id);
        return this.toDeferredResult(result);
    }

    public Observable<HashMap<String,User>> aggregationObservable(Long id) {
        // 合并两个或多个Observables发射出的数据项，根据指定的函数变换它们
        return Observable.zip(this.aggregationService.getUserById(id) , this.aggregationService.getMovieUserByUserId(id) , (user , movieUser) -> {
            HashMap<String, User> map = Maps.newHashMap();
            map.put("user" , user);
            map.put("movieUser" , movieUser);
            return map;
        });

    }

    public DeferredResult<HashMap<String, User>> toDeferredResult(Observable<HashMap<String, User>> details) {
        DeferredResult<HashMap<String, User>> result = new DeferredResult<>();
        // 订阅
        details.subscribe(new Observer<HashMap<String, User>>() {
            @Override
            public void onCompleted() {
                LOGGER.info("完成...");
            }

            @Override
            public void onError(Throwable e) {
                LOGGER.info("发生异常...",e);
            }

            @Override
            public void onNext(HashMap<String, User> stringUserHashMap) {
                result.setResult(stringUserHashMap);
            }
        });
        return result;
    }
}
